import {Injectable} from '@angular/core';
import {
  CanActivate, // 守卫，处理导航到某路由的情况。
  ActivatedRouteSnapshot,
  RouterStateSnapshot, Router
} from '@angular/router';
import {environment} from '../../environments/environment';
import {CommonTool} from '../common/common.tool';
import {LoginDto} from './base.model';

@Injectable()
export class BaseRouteFilter implements CanActivate {
  constructor(private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const token = CommonTool.getCookie(environment.tokenKey);
    if (CommonTool.notNull(token)) {
      const tokenModel: LoginDto = new LoginDto(JSON.parse(token));
      const date = CommonTool.turnDate(tokenModel.updateTime);
      if ((date.getTime() + tokenModel.validTime) > new Date().getTime()) {
        return true;
      }
    }
    this.router.navigate(['/login']);
    return false;
  }


}
